<template>
    <div class="address-eidt-contain">
        <div class="header bg-grey">
            <div class="header-left">
                <div class="back" @click="handleReturn">
                    <i class="i-left"></i>
                </div>
            </div>
            <div class="header-middle"><span class="font-black">添加收货地址</span></div>
            <div class="header-right">
                <button class="btn-save-addr" :disabled = "btnDisabled" @click="handleSave">保存</button>
            </div>
        </div>
        <div class="content">
            <van-cell-group>
                <van-field v-model="addrForm.userName" label="收货人" placeholder="请输入收货人" :error-message=errorMsg.userName></van-field>
                <van-field v-model="addrForm.telNumber" label="手机号码" placeholder="请输入手机号码" :error-message=errorMsg.telNumber ></van-field>
                <van-field v-model="addrForm.area" readonly label="所在地区" placeholder="请输入所在地区" @focus = "showArea" :error-message=errorMsg.area ></van-field>
                <van-field v-model="addrForm.detailInfo" label="详细地址" placeholder="请输入详细地址" :error-message=errorMsg.detailInfo autosize ></van-field>
                <div class="add-default">
                    <span class="add-default-left">设置为默认地址</span>
                    <span class="add-default-right"><van-switch   size="20px" active-color="#07c160" v-model="addr_default" /></span>
                </div>
            </van-cell-group>
        </div>
        <van-popup v-model="show" position="bottom" >
            <citylist v-on:confirm="setArea" v-on:cancel="areaCancel"></citylist>
        </van-popup>
    </div>

</template>

<script>
import citylist from "@/components/citylist"
import { addressSave, getAddressDetail } from "@/api/user"
import { validateMobile,validateCode } from '@/utils/rule'
import validator from '@/utils/validator'
import { Toast } from 'vant'
import { autoLogin } from "@/utils"

export default {
    name: "address-edit",
    components: { citylist},
    data() {
        const validatePhone = (rule, value, callback) => {
            if (!validateMobile(value)) {
                callback(new Error('请输入正确的手机号'))
            } else {
                callback()
            }
        };
        const validatePostalCode= (rule, value, callback) => {
            if (!validateCode(value)) {
                callback(new Error('请输入正确的邮政编码'))
            } else {
                callback()
            }
        };
        return {
            show: false,
            addr_default: true,
            btnDisabled: false,
            area_text: "请选择所在地区",
            addrForm: {
                userName: "",
                provinceName: "",
                cityName: "",
                countyName: "",
                streetName: "",
                detailInfo: "",
                nationalCode: "",
                postalCode: "",
                telNumber: "",
                is_default: 0,
                area: "",
                addressId: 0
            },
            errorMsg: {
                userName : '',
                telNumber: '',
                area: '',
                detailInfo: '',
                // postalCode: ''
            },
            rules: {
                userName : [ {required: true, message: '请输入名称'}],
                telNumber: [{validator: validatePhone, message: '请输入正确的手机号'}],
                area: [{required: true, message: '请选择所在地区'}],
                detailInfo: [{required: true, message: '请输入详细地址'}],
                // postalCode: [{validator:validatePostalCode,message: '请输入正确的邮政编码'}]
            }
        }
    },
    created(){
        autoLogin()
        this.validator = validator(this.rules, this.addrForm);
        this.getDetail();
    },
    methods: {
        handleReturn() {
            this.$router.go(-1)
        },
        getDetail() {
            const data = {}
            data.id = ""
            getAddressDetail(data).then(response => {
                if (response.data) {
                    this.addr_default = false
                }
            })
        },
        setArea(value){
            var area = ""
            if(value[0] && value[0].text){
                area += value[0].text
                this.addrForm.provinceName = value[0].text
            }
            if(value[1] && value[1].text){
                area += "/" + value[1].text
                this.addrForm.cityName = value[1].text
            }
            if(value[2] && value[2].text){
                area += "/" + value[2].text
                this.addrForm.countyName = value[2].text
                this.addrForm.nationalCode = value[2].id
            }
            if(value[3] && value[3].text){
                area += "/" + value[3].text
                this.addrForm.streetName = value[3].text
                this.addrForm.addressId = value[3].id
            }
            this.addrForm.area = area
            this.area_text = area
            this.show = false
        },
        areaCancel() {
            this.show = false
            this.area_text = "请选择所在地区"
        },
        showArea() {
            this.show = true
        },
        handleSave(){
            const self = this
            this.btnDisabled = true,
            this.validate((errors, fields) => {
                if (errors === false){
                    self.addrForm.is_default = self.addr_default ? 1 : 0
                    addressSave(self.addrForm).then(response=>{
                        self.btnDisabled = false
                        if(response.data){
                            Toast.success('保存成功')
                            setTimeout(() => {
                                this.$router.go(-1);
                                // this.$router.push({path: '/address'})
                            }, 3 * 1000)
                        }
                    })
                } else {
                    self.btnDisabled = false
                }
            })
        },
        /**
         * 清除验证提示
         * @param attrs
         */
        resetField(attrs) {
            attrs = !attrs ? Object.keys(this.errorMsg) : ( Array.isArray(attrs) ? attrs : [attrs]);
            attrs.forEach(attr => {
                this.errorMsg[attr] = ''
            })
        },
        /**
         * 验证方法
         * @param callback
         * @param data
         */
        validate(callback, data) {
            this.validator.validate((errors, fields) => {
                this.resetField();
                if (errors) {
                    fields.forEach(item => {
                        this.errorMsg[item.field] = item.message
                    })
                }
                callback && callback(errors, fields)
            }, data);
        },
    }
}
</script>
